package com.elysia.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.elysia.common.Constants;
import com.elysia.common.Result;
import com.elysia.entity.User;
import com.elysia.entity.dto.UserDto;
import com.elysia.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

//    @Autowired
//    private UserMapper userMapper;

    @Autowired
    private IUserService userService;

    //查询
    @GetMapping("/findAll")
    public Result findAll(){
        return Result.success(userService.list());
    }

    @PostMapping("/update")
    //修改
    public Result update(@RequestBody User user){
        return Result.success(userService.updateById(user));
    }

    @PostMapping("/add")
    //添加
    public Result add(@RequestBody User user){
        return Result.success(userService.save(user));
    }

    @DeleteMapping("/delete/{id}")
    //删除
    public Result delete(@PathVariable Integer id){
        return Result.success(userService.removeById(id));
    }

    //分页查询
    @GetMapping("/findPage")
    public Result findPage(@RequestParam Integer pageNum,
                                       @RequestParam Integer pageSize,
                                       @RequestParam(defaultValue = "") String username,
                                       @RequestParam(defaultValue = "") String email,
                                       @RequestParam(defaultValue = "") String address
//                                       @RequestParam(defaultValue = "") String avatarUrl
    ){
//        IPage<User> page = new Page<>(pageNum,pageSize);
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        if (username != null){
//            queryWrapper.like("username",username);
//        }
//        if (email != null){
//            queryWrapper.like("email",email);
//        }
//        if (address != null){
//            queryWrapper.like("address",address);
//        }
//        if (avatarUrl != null){
//            queryWrapper.like("avatarUrl",avatarUrl);
//        }
        return Result.success(userService.findPage(new Page<>(pageNum,pageSize), username, email, address));
    }

    //批量删除
    @PostMapping("/delete")
    public Result deleteByIds(@RequestBody List<Integer> ids){
        return Result.success(userService.removeBatchByIds(ids));
    }

    /**
     * 导出接口
     * 思路：
     * 1. GetMapping注解
     * 2. List集合封装
     * 3. ExcelUtil工具类（getWriter）
     * 4. 设置浏览器响应格式
     * 5. 刷新流 关流
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库查询数据
        List<User> list = userService.list();
        //通过工具类创建writer
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        //在内存操作 写到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        //自定义标题别名
        /**
         * addHeaderAlias(String name, String alias)
         * name-原名
         * alias-别名
         */
        writer.addHeaderAlias("username","用户名");
        writer.addHeaderAlias("password","密码");
        writer.addHeaderAlias("nickname","昵称");
        writer.addHeaderAlias("email","邮箱");
        writer.addHeaderAlias("phone","电话");
        writer.addHeaderAlias("address","地址");
        writer.addHeaderAlias("createTime","创建时间");
        writer.addHeaderAlias("avatarUrl","头像");
//
        //一次性写出list内对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        //刷新流 关流
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * 导入接口
     * 思路：
     * 1. PostMapping注解
     * 2. List集合
     * 3. 迭代器遍历设置数据
     */
    @PostMapping("import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        //忽略表头的中文，直接读取表的内容
        /**
         * 读取工作簿中指定的Sheet
         * startRowIndex – 起始行（包含，从0开始计数）
         * Returns:行的集合，一行使用List表示
         */
        List<List<Object>> list = reader.read(1);
        ArrayList<User> users = CollUtil.newArrayList();

        //遍历
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            user.setAvatarUrl(row.get(6).toString());
            users.add(user);
        }

        /**
         * 插入批量
         * entityList – 实体对象集合
         * default boolean saveBatch(Collection<T> entityList)
         */
        userService.saveBatch(users);
        return Result.success(true);
    }

    /**
     * 登陆
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto){
        //获得前端的数据
        String username = userDto.getUsername();
        String password = userDto.getPassword();

        //进行校验
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_401,"参数错误");
        }
        UserDto Dto = userService.login(userDto);
        return Result.success(Dto);
    }

    //注册
    @PostMapping("/register")
    //添加
    public Result register(@RequestBody UserDto userDto){
        //获取用户账号密码
        String username = userDto.getUsername();
        String password = userDto.getPassword();

        //判断
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_401,"参数错误");
        }
        return Result.success(userService.register(userDto));
    }

    /**
     * 根据名字修改个人信息
     */
    @GetMapping("/username/{username}")
    public Result findByUsername(@PathVariable String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return Result.success(userService.getOne(queryWrapper));
    }
}
